Crate leptos

source ·
Expand description

About Leptos

Leptos is a full-stack framework for building web applications in Rust. You can use it to build

  • single-page apps (SPAs) rendered entirely in the browser, using client-side routing and loading or mutating data via async requests to the server
  • multi-page apps (MPAs) rendered on the server, managing navigation, data, and mutations via web-standard <a> and <form> tags
  • progressively-enhanced single-page apps that are rendered on the server and then hydrated on the client, enhancing your <a> and <form> navigations and mutations seamlessly when WASM is available.

And you can do all three of these using the same Leptos code.

Take a look at the Leptos Book for a walkthrough of the framework. Join us on our Discord Channel to see what the community is building. Explore our Examples to see Leptos in action.

Learning by Example

If you want to see what Leptos is capable of, check out the examples:

  • counter is the classic counter example, showing the basics of client-side rendering and reactive DOM updates
  • counter_without_macros adapts the counter example to use the builder pattern for the UI and avoids other macros, instead showing the code that Leptos generates.
  • counters introduces parent-child communication via contexts, and the <For/> component for efficient keyed list updates.
  • counters_stable adapts the counters example to show how to use Leptos with stable Rust.
  • error_boundary shows how to use Result types to handle errors.
  • parent_child shows four different ways a parent component can communicate with a child, including passing a closure, context, and more
  • fetch introduces Resources, which allow you to integrate arbitrary async code like an HTTP request within your reactive code.
  • router shows how to use Leptos’s nested router to enable client-side navigation and route-specific, reactive data loading.
  • slots shows how to use slots on components.
  • counter_isomorphic shows different methods of interaction with a stateful server, including server functions, server actions, forms, and server-sent events (SSE).
  • todomvc shows the basics of building an isomorphic web app. Both the server and the client import the same app code from the todomvc example. The server renders the app directly to an HTML string, and the client hydrates that HTML to make it interactive. You might also want to see how we use create_effect to serialize JSON to localStorage and reactively call DOM methods on references to elements.
  • hackernews and hackernews_axum integrate calls to a real external REST API, routing, server-side rendering and hydration to create a fully-functional application that works as intended even before WASM has loaded and begun to run.
  • todo_app_sqlite, todo_app_sqlite_axum, and todo_app_sqlite_viz show how to build a full-stack app using server functions and database connections.
  • tailwind shows how to integrate TailwindCSS with cargo-leptos.

Details on how to run each example can be found in its README.

Here are links to the most important sections of the docs:

Feature Flags

  • nightly: On nightly Rust, enables the function-call syntax for signal getters and setters.
  • csr Client-side rendering: Generate DOM nodes in the browser
  • ssr Server-side rendering: Generate an HTML string (typically on the server)
  • hydrate Hydration: use this to add interactivity to an SSRed Leptos app
  • serde (Default) In SSR/hydrate mode, uses serde to serialize resources and send them from the server to the client.
  • serde-lite In SSR/hydrate mode, uses serde-lite to serialize resources and send them from the server to the client.
  • rkyv In SSR/hydrate mode, uses rkyv to serialize resources and send them from the server to the client.
  • miniserde In SSR/hydrate mode, uses miniserde to serialize resources and send them from the server to the client.
  • tracing Adds additional support for tracing to components.
  • default-tls Use default native TLS support. (Only applies when using server functions with a non-WASM client like a desktop app.)
  • rustls Use rustls. (Only applies when using server functions with a non-WASM client like a desktop app.)
  • template_macro Enables the template! macro, which offers faster DOM node creation for some use cases in csr.

Important Note: You must enable one of csr, hydrate, or ssr to tell Leptos which mode your app is operating in. You should only enable one of these per build target, i.e., you should not have both hydrate and ssr enabled for your server binary, only ssr.

A Simple Counter

use leptos::*;

#[component]
pub fn SimpleCounter(cx: Scope, initial_value: i32) -> impl IntoView {
    // create a reactive signal with the initial value
    let (value, set_value) = create_signal(cx, initial_value);

    // create event handlers for our buttons
    // note that `value` and `set_value` are `Copy`, so it's super easy to move them into closures
    let clear = move |_| set_value.set(0);
    let decrement = move |_| set_value.update(|value| *value -= 1);
    let increment = move |_| set_value.update(|value| *value += 1);

    // this JSX is compiled to an HTML template string for performance
    view! {
        cx,
        <div>
            <button on:click=clear>"Clear"</button>
            <button on:click=decrement>"-1"</button>
            <span>"Value: " {move || value.get().to_string()} "!"</span>
            <button on:click=increment>"+1"</button>
        </div>
    }
}

Leptos is easy to use with Trunk (or with a simple wasm-bindgen setup):


#[component]
fn SimpleCounter(cx: Scope, initial_value: i32) -> impl IntoView {
    todo!()
}

pub fn main() {
    mount_to_body(|cx| view! { cx,  <SimpleCounter initial_value=3 /> })
}

Re-exports

Modules

  • Types to make it easier to handle errors in your application.
  • Types for all DOM events.
  • Exports types for working with HTML elements.
  • Exports types for working with MathML elements.
  • Utilities for exporting nonces to be used for a Content Security Policy.
  • This prelude imports all signal types as well as all signal traits needed to use those types.
  • Utilities for server-side rendering HTML.
  • Types that handle asynchronous data loading via <Suspense/>.
  • Exports types for working with SVG elements.

Macros

  • Uses println!()-style formatting to log warnings to the console (in the browser) or via eprintln!() (if not in the browser), but only if it’s a debug build.
  • Uses println!()-style formatting to log errors to the console (in the browser) or via eprintln!() (if not in the browser).
  • Uses println!()-style formatting to log something to the console (in the browser) or via println!() (if not in the browser).
  • The view macro uses RSX (like JSX, but Rust!) It follows most of the same rules as HTML, with the following differences:
  • The view macro uses RSX (like JSX, but Rust!) It follows most of the same rules as HTML, with the following differences:
  • Uses println!()-style formatting to log warnings to the console (in the browser) or via eprintln!() (if not in the browser).

Structs

Enums

  • Represents the different possible values an attribute node could have.
  • Represents the different possible values a single class on an element could have, allowing you to do fine-grained updates to single items in Element.classList.
  • A wrapper for a value that is either T or Signal<T>.
  • Represents the different possible values an element property could have, allowing you to do fine-grained updates to single fields.
  • Describes errors that can occur while serializing and deserializing data, typically during the process of streaming Resources from the server to the client.
  • Type for errors that can occur when using server functions.
  • Type for errors that can occur when using server functions.
  • A leptos view which can be mounted to the DOM.

Traits

  • Collects an iterator or collection into a View.
  • Converts some type into an Attribute.
  • Converts some type into a Class.
  • Converts some type into a Property.
  • Helper trait for converting Fn() -> T closures into Signal<T>.
  • Helper trait for converting Fn(T) into SignalSetter<T>.
  • Converts some type into a Style.
  • Converts the value into a View.
  • Describes an object that can be serialized to or from a supported format Currently those are JSON and Cbor
  • Defines a “server function.” A server function can be called from the server or the client, but the body of its code will only be run on the server, i.e., if a crate feature ssr is enabled.
  • This trait allows disposing a signal before its Scope has been disposed.
  • This trait allows getting an owned value of the signals inner type.
  • Trait implemented for all signal types which you can get a value from, such as ReadSignal, Memo, etc., which allows getting the inner value without subscribing to the current scope.
  • This trait allows setting the value of a signal.
  • Trait implemented for all signal types which you can set the inner value, such as WriteSignal and RwSignal, which allows setting the inner value without causing effects which depend on the signal from being run.
  • This trait allows converting a signal into a async [Stream].
  • This trait allows updating the inner value of a signal.
  • This trait allows updating the signals value without causing dependant effects to run.
  • This trait allows obtaining an immutable reference to the signal’s inner type.
  • This trait allows getting a reference to the signals inner value without creating a dependency on the signal.

Functions

  • A component that will show its children when the when condition is true. Additionally, you need to specify a hide_delay. If the when condition changes to false, the unmounting of the children will be delayed by the specified Duration. If you provide the optional show_class and hide_class, you can create very easy mount / unmount animations.
  • Allows you to inline the data loading for an async block or server function directly into your view. This is the equivalent of combining a create_resource that only loads once (i.e., with a source signal || ()) with a Suspense with no fallback. Adding bind:{variable name} to the props makes the data available in the children that variable name, when resolved.
  • When you render a Result<_, _> in your view, in the Err case it will render nothing, and search up through the view tree for an <ErrorBoundary/>. This component lets you define a fallback that should be rendered in that error case, allowing you to handle errors within a section of the interface.
  • Iterates over children and displays them, keyed by the key function given. This is much more efficient than naively iterating over nodes with .iter().map(|n| view! { cx, ... })..., as it avoids re-creating DOM nodes that are not being changed.
  • A component that will show its children when the when condition is true, and show the fallback when it is false, without rerendering every time the condition changes. Note: Because of the nature of generic arguments, it’s not really possible to make the fallback optional. If you want an empty fallback state—in other words, if you want to show the children if when is true and noting otherwise—use fallback=|_| () (i.e., a fallback function that returns the unit type ()).
  • If any Resources are read in the children of this component, it will show the fallback while they are loading. Once all are resolved, it will render the children. Note that the children will be rendered initially (in order to capture the fact that those resources are read under the suspense), so you cannot assume that resources have Some value in children.
  • If any Resources are read in the children of this component, it will show the fallback while they are loading. Once all are resolved, it will render the children. Unlike Suspense, this will not fall back to the fallback state if there are further changes after the initial load. Note that the children will be rendered initially (in order to capture the fact that those resources are read under the suspense), so you cannot assume that resources have Some value in children.
  • Creates an Action to synchronize an imperative async call to the synchronous reactive system.
  • Creates a “blocking” Resource. When server-side rendering is used, this resource will cause any <Suspense/> you read it under to block the initial chunk of HTML from being sent to the client. This means that if you set things like HTTP headers or <head> metadata in that <Suspense/>, that header material will be included in the server’s original response.
  • Effects run a certain chunk of code whenever the signals they depend on change. create_effect immediately runs the given function once, tracks its dependence on any signal values read within it, and reruns the function whenever the value of a dependency changes.
  • Creates an effect; unlike effects created by create_effect, isomorphic effects will run on the server as well as the client.
  • Creates a local Resource, which is a signal that reflects the current state of an asynchronous task, allowing you to integrate async Futures into the synchronous reactive system.
  • Creates a local Resource with the given initial value, which will only generate and run a Future using the fetcher when the source changes.
  • Works exactly as create_signal, but creates multiple signals at once.
  • Works exactly as create_many_signals, but applies the map function to each signal pair.
  • Creates an efficient derived reactive value based on other reactive values.
  • Creates an MultiAction to synchronize an imperative async call to the synchronous reactive system.
  • Creates a shared reference to a DOM node created while using the view macro to create your UI.
  • Takes a memoized, read-only slice of a signal. This is equivalent to the read-only half of create_slice.
  • Creates a Resource, which is a signal that reflects the current state of an asynchronous task, allowing you to integrate async Futures into the synchronous reactive system.
  • Creates a Resource with the given initial value, which will only generate and run a Future using the fetcher when the source changes.
  • Creates a reactive signal with the getter and setter unified in one value. You may prefer this style, or it may be easier to pass around in a context or as a function argument.
  • Creates a conditional signal that only notifies subscribers when a change in the source signal’s value changes whether it is equal to the key value (as determined by PartialEq.)
  • Creates a conditional signal that only notifies subscribers when a change in the source signal’s value changes whether the given function is true.
  • Creates an Action that can be used to call a server function.
  • Creates an MultiAction that can be used to call a server function.
  • Creates a signal, the basic reactive primitive.
  • Creates a signal that always contains the most recent value emitted by a Stream. If the stream has not yet emitted a value since the signal was created, the signal’s value will be None.
  • Derives a reactive slice of an RwSignal.
  • Creates a Trigger, a kind of reactive primitive.
  • Creates a setter to access one slice of a signal. This is equivalent to the write-only half of create_slice.
  • “Debounce” a callback function. This will cause it to wait for a period of delay after it is called. If it is called again during that period, it will wait delay before running, and so on. This can be used, for example, to wrap event listeners to prevent them from firing constantly as you type.
  • Returns the Document.
  • Helper function to extract Event.target from any event.
  • Helper function to extract event.target.checked from an event.
  • Helper function to extract event.target.value from an event.
  • Extracts a context value of type T from the reactive system by traversing it upwards, beginning from the current Scope and iterating through its parents, if any. The context value should have been provided elsewhere using provide_context.
  • Loads LeptosOptions from a Cargo.toml with layered overrides. If an env var is specified, like LEPTOS_ENV, it will override a setting in the file. It takes in an optional path to a Cargo.toml file. If None is provided, you’ll need to set the options as environment variables or rely on the defaults. This is the preferred approach for cargo-leptos. If Some(“./Cargo.toml”) is provided, Leptos will read in the settings itself. This option currently does not allow dashes in file or folder names, as all dashes become underscores
  • Gets the value of a property set on a DOM element.
  • Returns the current window.location.
  • Current window.location.hash without the beginning #.
  • Runs the provided closure and mounts the result to the provided element.
  • Runs the provided closure and mounts the result to the <body>.
  • Creates a cleanup function, which will be run when a Scope is disposed.
  • Provides a context value of type T to the current reactive Scope and all of its descendants. This can be consumed using use_context.
  • The microtask is a short function which will run after the current task has completed its work and when there is no other code waiting to be run before control of the execution context is returned to the browser’s event loop.
  • Runs the given function between the next repaint using Window.requestAnimationFrame.
  • Runs the given function between the next repaint using Window.requestAnimationFrame, returning a cancelable handle.
  • Queues the given function during an idle period using Window.requestIdleCallback.
  • Queues the given function during an idle period using Window.requestIdleCallback, returning a cancelable handle.
  • Repeatedly calls the given function, with a delay of the given duration between calls. See setInterval().
  • Repeatedly calls the given function, with a delay of the given duration between calls, returning a cancelable handle. See setInterval().
  • Sets a property on a DOM element.
  • Executes the given function after the given duration of time has passed. setTimeout().
  • Executes the given function after the given duration of time has passed, returning a cancelable handle. setTimeout().
  • Spawns and runs a thread-local Future in a platform-independent way.
  • Creates a non-reactive wrapper for any value by storing it within the reactive system.
  • Extracts a context value of type T from the reactive system by traversing it upwards, beginning from the current Scope and iterating through its parents, if any. The context value should have been provided elsewhere using provide_context.
  • A version of create_effect that listens to any dependency that is accessed inside deps and returns a stop handler. The return value of deps is passed into callback as an argument together with the previous value. Additionally the last return value of callback is provided as a third argument as is done in create_effect.
  • Returns the Window.
  • Creates a window event listener from a typed event.
  • Adds an event listener to the Window, typed as a generic Event.

Type Definitions

  • A type for taking anything that implements IntoAttribute.
  • The most common type for the children property on components, which can only be called once.
  • A type for the children property on components that can be called more than once.
  • A type for the children property on components that can be called more than once, but may mutate the children.

Attribute Macros

  • Annotates a function so that it can be used with your template as a Leptos <Component/>.
  • Declares that a function is a server function. This means that its body will only run on the server, i.e., when the ssr feature is enabled.
  • Annotates a struct so that it can be used with your Component as a slot.

Derive Macros

  • Derives a trait that parses a map of string keys and values into a typed data structure, e.g., for route params.